﻿/* $RCSFile: DownLoadGenerator.aspx.cs $
 * Apache license v2 2011 by Christian Surieux
 * $Source: ?/AddonNice.EMailing/PageModules/DownloadSession/DownLoadGenerator.aspx.cs $
 * $log$
 * Revision 23 2010/08/09 11:12:45  christian.surieux
 *   Added Log comment to all .ascx .aspx .master files
 * Revision 10 2010/08/09 10:13:18  christian.surieux
 *   Added Log comment to all cs files
 */

using System;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Globalization;

using AddonNice.UI;
using AddonNice.Settings;
using AddonNice.UI.WebControls;
using AddonNice.Security;
using AddonNice.Configuration;
using AddonNice.Diagnostics;
using AddonNice.Helpers;
using AddonNice.Authentication;
using AddonNice.CRMEMailing;
using AddonNice.Settings.CRMEMailing;

using Telerik.Web.UI;

using Trace2    =   System.Diagnostics.Trace;
using Path2     =   AddonNice.Settings.Path;


namespace AddonNice.PageModules.DownloadSession
{
    /// <summary>
    /// Send a file when the user has clicked on on link in a privatedownload
    /// Receive in its parameters the DB id of the PrivateDocument: get the associated file and send it on the reponse stream
    /// </summary>
    public partial class DownLoadGenerator : Page
    {
        XrmEMailingDB dwnDB   =   new XrmEMailingDB();

        protected void Page_Load(object sender, EventArgs e)
        {
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadGenerator Page_Load BEG Request.IsAuthenticated: {0}.",Request.IsAuthenticated),ModuleTraceSwitch.Sw.Info);
            if (IsPostBack || !Request.IsAuthenticated )
            {
                PortalSecurity.AccessDenied();
            }
            string VersionFileName          =   string.Empty;
            SqlDataReader dr                =   null;
            try
            {
                string versionIdStr         =   Request.Params["id"];
                string UserDownLoadStr      =   Request.Params["crmid"];
                //int UserDownLoadId      =   int.Parse(UserDownLoadStr);
                int VersionFileId           =   int.Parse(versionIdStr);
			    if ( ModuleTraceSwitch.Sw.TraceVerbose )
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadGenerator Page_Load VersionFileId: {0}, UserDownLoadStr: {1}",VersionFileId,UserDownLoadStr),ModuleTraceSwitch.Sw.Info);
                dr                          =   dwnDB.GetPrivateDocumentFull(VersionFileId) ;
                if ( dr.Read() )
                {
                    string Title            =   (string)dr[AStr.DBTitle];
                    VersionFileName         =   (string)dr[AStr.DBFilename];
                    int ContentSize         =   (int)dr[AStr.DBContenSize];
                    int idx                 =   VersionFileName.LastIndexOf('.');
                    string ContentType      =   "application/octet-stream";
                    if (( idx > -1 ) && ( idx < VersionFileName.Length ) )
                    {
                        string ext          =   VersionFileName.Substring(idx+1);
                         ContentType        =   DocumentsHelper.GetImage(ext);
                    }
                    dr.Close();
                    dr                      =   null;
                    byte[] buffer           =   dwnDB.GetPrivateDocumentContent(VersionFileId);
			        if ( ModuleTraceSwitch.Sw.TraceVerbose )
                        Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[V]DownLoadGenerator Page_Load BinProduct.Length: {0}",buffer.Length),ModuleTraceSwitch.Sw.Info);
			        Response.ClearHeaders();
			        Response.ClearContent();
                    //Response.Headers.Add("title",Title);
			        Response.ContentType	=  ContentType; 
			        Response.AddHeader("Content-Disposition", "attachment; filename=" + VersionFileName);
				    Response.BinaryWrite(buffer);
			    }
			}
			catch(Exception ex)
			{
				if (ModuleTraceSwitch.Sw.TraceError)
                    Trace2.WriteLine( string.Format(CultureInfo.InvariantCulture,"[E]DownLoadGenerator Page_Load filename: {0}, ex: {1}",VersionFileName,ex),ModuleTraceSwitch.Sw.Info);
                if ( dr != null )
                    dr.Close();
                throw;
			}
			if (ModuleTraceSwitch.Sw.TraceVerbose)
                Trace2.WriteLine("[V]DownLoadGenerator Page_Load END.",ModuleTraceSwitch.Sw.Info);
			Response.End();
        }
    }
}
